import router,{resetRouter} from '@/router'
import store from '@/store'
import { Message } from 'element-ui'
import asyncRoutes from '@/router/asyncRoutes'
function getFirstRoutePermission(permision){
  const firstPermissionArr = permision.map(item =>{
    return item.split(':')[0]
  })
  console.log(firstPermissionArr)
  // 去重 
  return Array.from(new Set(firstPermissionArr))
}
function getSecondRoutePermission(permission){
  const secondPermArr = permission.map(item => {
    const arr = item.split(':')
    return `${arr[0]}:${arr[1]}`
  })
  return Array.from(new Set(secondPermArr))
}
function getRoutes(firstPermission,secondPermission,asyncRoutes){
  if(firstPermission[0]==='*') return asyncRoutes
  const firstRoutes = asyncRoutes.filter(item => firstPermission.includes(item.permision))
  const routes = firstRoutes.map(item => {
    return {
      ...item,
      children: item.children.filter(child => secondPermission.includes(child.permision))
    }
  })
  return routes
}
router.beforeEach(async (to, from, next) => {
  // 1.获取token
  const token = store.state.user.token
  const whiteList = ['/login', '/404']
  // 2.判断是否有token
  if (token) {
    // 2.1 如果有token，判断是否是登录页
    next()
    if (to.path === '/login') {
      store.commit('permission/clearMenuList')
      resetRouter()
      next('/')
    } else {
      // fetch('https://api-hmzs.itheima.net/v1//park/sys/permision/all/tree').then((res)=>{
      //   console.log(res)
      // })
      const permision = await store.dispatch('permission/getProfile')
      // 根据权限标识筛选出路由
      const firstPermission = getFirstRoutePermission(permision)

      const secondPermission   = getSecondRoutePermission(permision)
      const routes = getRoutes(firstPermission,secondPermission,asyncRoutes)
      routes.forEach((item)=>router.addRoute(item))
      console.log(routes)
      store.commit('permission/setMenuList',routes)
    }
  } else {
    // 2.2 如果没有token，判断是否在白名单中
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      Message.warning('请先登录')
      next('/login')
    }
  }
})
